package com.zz.nondatain.view.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.zz.nondatain.OtherActivity;
import com.zz.nondatain.R;
import com.zz.nondatain.base.BaseFragment;
import com.zz.nondatain.databinding.FragmentProfileBinding;
import com.zz.nondatain.utils.PrefsManager;
import com.zz.nondatain.view.activity.AboutActivity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class ProfileFragment extends BaseFragment<FragmentProfileBinding> {

    private static final String START_DATE = "2022-04-13";
    private static final String END_DATE = "2028-04-13";
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private PrefsManager prefsManager;

    public static ProfileFragment newInstance() {
        return new ProfileFragment();
    }

    @Override
    protected void initView() {
        // 初始化PrefsManager
        prefsManager = PrefsManager.getInstance(requireContext());

        // 设置进度条和日期信息
        setupProgress();

        // 设置点击事件
        setupClickListeners();

        // 更新摄像头选择显示
        updateCameraTypeDisplay();
    }

    private void updateCameraTypeDisplay() {
        // 从PrefsManager获取保存的相机类型
        String cameraType = prefsManager.getCameraType();

        // 在UI中显示选择的相机类型
        TextView cameraTextView = binding.layoutFaceScan.findViewById(R.id.tv_camera_type);
        if (cameraTextView != null) {
            cameraTextView.setText(cameraType);
        }
    }

    private void setupProgress() {
        try {
            // 计算开始到现在的天数
            Date startDate = dateFormat.parse(START_DATE);
            Date endDate = dateFormat.parse(END_DATE);
            Date currentDate = new Date();

            if (startDate != null && endDate != null) {
                long totalDays = TimeUnit.MILLISECONDS.toDays(endDate.getTime() - startDate.getTime());
                long passedDays = TimeUnit.MILLISECONDS.toDays(currentDate.getTime() - startDate.getTime());

                // 设置进度条
                int progress = (int) ((float) passedDays / totalDays * 100);
                binding.progressBar.setProgress(progress);

                // 设置已开始天数
                binding.tvStartDays.setText("已开始: " + passedDays + "天");

                // 设置截止日期
                SimpleDateFormat displayFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
                binding.tvEndDate.setText("截止于" + displayFormat.format(endDate));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void setupClickListeners() {
        // 面部图像点击事件
        binding.layoutFaceImage.setOnClickListener(v -> startOtherActivity());

        // 人脸扫描点击事件 - 显示相机选择底部弹窗
        binding.layoutFaceScan.setOnClickListener(v -> showCameraChooserDialog());

        // 绑定设备 - 不需要点击事件，只显示设备信息

        // 检查更新点击事件
        binding.layoutCheckUpdate.setOnClickListener(v -> showUpdateDialog());

        // 关于我们点击事件
        binding.layoutAbout.setOnClickListener(v -> startAboutActivity());

        // 退出登录点击事件
        binding.btnLogout.setOnClickListener(v -> showLogoutDialog());
    }

    /**
     * 显示相机选择底部弹出对话框
     */
    private void showCameraChooserDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(requireContext());
        View view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_camera_chooser, null);
        dialog.setContentView(view);

        // 设置点击事件
        view.findViewById(R.id.tv_front_camera).setOnClickListener(v -> {
            // 保存相机选择
            prefsManager.saveCameraType(PrefsManager.CAMERA_FRONT);
            // 更新UI显示
            updateCameraTypeDisplay();
            // 关闭对话框
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_back_camera).setOnClickListener(v -> {
            // 保存相机选择
            prefsManager.saveCameraType(PrefsManager.CAMERA_BACK);
            // 更新UI显示
            updateCameraTypeDisplay();
            // 关闭对话框
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> dialog.dismiss());

        // 点击空白区域可取消
        dialog.setCancelable(true);

        dialog.show();
    }

    private void startOtherActivity() {
        Intent intent = new Intent(requireContext(), OtherActivity.class);
        startActivity(intent);
    }

    /**
     * 跳转到关于我们页面
     */
    private void startAboutActivity() {
        Intent intent = new Intent(requireContext(), AboutActivity.class);
        startActivity(intent);
    }

    private void showUpdateDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("检查更新")
                .setMessage("当前应用为最新版本")
                .setPositiveButton("确定", null)
                .show();
    }

    private void showLogoutDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    showToast("已退出登录");
                    // 实际应用中，这里应该跳转到登录页面
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    protected void initData() {
        // 初始化数据
    }

    @Override
    protected void initObservers() {
        // 初始化观察者
    }

    @Override
    protected FragmentProfileBinding getViewBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentProfileBinding.inflate(inflater, container, false);
    }
} 